package com.qd.panda.service.wallet.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.excel.ExcelExport;
import com.cdqidi.excel.util.ExportPage;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.DateUtil;
import com.cdqidi.util.RedisTemplateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.wallet.user.UserWalletRechargeLogDTO;
import com.qd.common.panda.domain.entity.wallet.user.UserWalletRechargeLogStatisticsDTO;
import com.qd.panda.mapper.wallet.user.UserWalletRechargeLogMapper;
import com.qd.panda.model.UserWalletRechargeLog;
import com.qd.panda.service.stroke.DisplayUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 用户钱包充值记录
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserWalletRechargeLogService extends BaseService<UserWalletRechargeLogMapper, UserWalletRechargeLog> {

    private static final String PREFIX_ID = "panda_user_wallet_recharge_log_orderId_{0}";

    private final RedisTemplateUtil<UserWalletRechargeLog> redisTemplateUtil;
    private final ObjectMapper objectMapper;
    @Resource
    private HttpServletResponse response;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserWalletRechargeLogDTO save(UserWalletRechargeLogDTO dto) {
        final UserWalletRechargeLog model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserWalletRechargeLogDTO update(UserWalletRechargeLogDTO dto) {
        final UserWalletRechargeLog historyModel = Optional.ofNullable(getById(dto.getOrderId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final UserWalletRechargeLog model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param orderId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String orderId) {
        final UserWalletRechargeLog historyModel = Optional.ofNullable(getById(orderId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(orderId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        final List<UserWalletRechargeLog> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(UserWalletRechargeLogDTO dto) {
        final QueryWrapper<UserWalletRechargeLog> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param orderId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String orderId) {
        boolean exists = false;
        if (StringUtils.hasLength(orderId)) {
            final UserWalletRechargeLog model = getById(orderId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param orderId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserWalletRechargeLog getById(String orderId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, orderId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(orderId), UserWalletRechargeLog.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param orderId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserWalletRechargeLogDTO getByIdDto(String orderId) {
        return Optional.ofNullable(getById(orderId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserWalletRechargeLog getOne(UserWalletRechargeLogDTO dto) {
        final QueryWrapper<UserWalletRechargeLog> queryWrapper = createQueryWrapper(dto);
        UserWalletRechargeLog model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserWalletRechargeLogDTO getOneDto(UserWalletRechargeLogDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<UserWalletRechargeLog> getList(UserWalletRechargeLogDTO dto) {
        final QueryWrapper<UserWalletRechargeLog> queryWrapper = createQueryWrapper(dto);
        final List<UserWalletRechargeLog> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<UserWalletRechargeLogDTO> getListDto(UserWalletRechargeLogDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserWalletRechargeLogDTO> page(Page<UserWalletRechargeLog> page, UserWalletRechargeLogDTO dto) {
        final QueryWrapper<UserWalletRechargeLog> queryWrapper = createQueryWrapper(dto);
        Page<UserWalletRechargeLog> iPage = baseMapper.selectPage(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(this::modelToDtoList);
        queryWrapper.clear();
        return iPage.convert(this::modelToDto);
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserWalletRechargeLogDTO> webPage(Page<UserWalletRechargeLog> page, UserWalletRechargeLogDTO dto) {
        final QueryWrapper<UserWalletRechargeLog> queryWrapper = createQueryWrapper(dto, "t1.", true);
        if (StringUtils.hasLength(dto.getMobile())) {
            queryWrapper.eq("t2.mobile", dto.getMobile());
        }
        final IPage<UserWalletRechargeLogDTO> iPage = baseMapper.page(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 查询可以退款的订单
     * @param userId 用户ID
     * @return 列表
     */
    @Transactional(readOnly = true)
    public List<UserWalletRechargeLogDTO> refundableOrders(String userId) {
        LocalDate end = LocalDate.now();
        LocalDate start = end.plusDays(-364);
        QueryWrapper<UserWalletRechargeLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("t1.user_id", userId);
        queryWrapper.eq("t1.pay_status",DisplayUtil.PAY_STATUS_1);
        queryWrapper.isNull("t2.refund_amount");
        queryWrapper.between("t1.recharge_time", DateUtil.localDateToStr(start)+" 00:00:00",DateUtil.localDateToStr(end)+" 23:59:59");
        List<UserWalletRechargeLogDTO> list = getBaseMapper().refundableOrders(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 导出Excel
     *
     * @param query 查询条件
     */
    @Transactional(readOnly = true)
    public void export(UserWalletRechargeLogDTO query) {
        final ExportPage<UserWalletRechargeLog, UserWalletRechargeLogDTO> exportPage = new ExportPage<>();
        try {
            final List<UserWalletRechargeLogDTO> list = exportPage.getAllForPage(page -> webPage(page, query).getRecords());
            try {
                ExcelExport.downloadExcel(response, UserWalletRechargeLogDTO.class, () -> list);
            } catch (IOException e) {
                log.error("导出失败", e);
                throw new ApiException("导出失败");
            }
        } finally {
            exportPage.freeData();
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(UserWalletRechargeLog model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getOrderId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<UserWalletRechargeLog> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getOrderId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public UserWalletRechargeLogDTO modelToDto(UserWalletRechargeLog model) {
        if (null == model) {
            return null;
        }
        final UserWalletRechargeLogDTO dto = new UserWalletRechargeLogDTO();
        dto.setOrderId(model.getOrderId());
        dto.setAllAmount(model.getAllAmount());
        dto.setGiveAmount(model.getGiveAmount());
        dto.setPayAmount(model.getPayAmount());
        dto.setRechargeTime(model.getRechargeTime());
        dto.setPayStatus(model.getPayStatus());
        dto.setRechargeType(model.getRechargeType());
        dto.setUserId(model.getUserId());
        dto.setPlanCode(model.getPlanCode());
        dto.setOperator(model.getOperator());
        dto.setOperateOrgId(model.getOperateOrgId());
        dto.setPublishId(model.getPublishId());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public UserWalletRechargeLog dtoToModel(UserWalletRechargeLogDTO dto) {
        if (null == dto) {
            return null;
        }
        final UserWalletRechargeLog model = new UserWalletRechargeLog();
        model.setOrderId(dto.getOrderId());
        model.setAllAmount(dto.getAllAmount());
        model.setGiveAmount(dto.getGiveAmount());
        model.setPayAmount(dto.getPayAmount());
        model.setRechargeTime(dto.getRechargeTime());
        model.setPayStatus(dto.getPayStatus());
        model.setRechargeType(dto.getRechargeType());
        model.setUserId(dto.getUserId());
        model.setPlanCode(dto.getPlanCode());
        model.setOperator(dto.getOperator());
        model.setOperateOrgId(dto.getOperateOrgId());
        model.setPublishId(dto.getPublishId());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(UserWalletRechargeLogDTO dto) {
        dto.setPayStatusDisplay(DisplayUtil.getPayStatusDisplay(dto.getPayStatus()));
        if (null != dto.getRechargeType()) {
            if (dto.getRechargeType() == PandaConstant.RECHARGE_TYPE_1) {
                dto.setRechargeTypeDisplay("自主充值");
            }
            if (dto.getRechargeType() == PandaConstant.RECHARGE_TYPE_2) {
                dto.setRechargeTypeDisplay("后台充值");
            }
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<UserWalletRechargeLogDTO> modelToDtoList(List<UserWalletRechargeLog> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<UserWalletRechargeLog> dtoToModelList(List<UserWalletRechargeLogDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<UserWalletRechargeLog> createQueryWrapper(UserWalletRechargeLogDTO dto) {
        return createQueryWrapper(dto, "", true);
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<UserWalletRechargeLog> createQueryWrapper(UserWalletRechargeLogDTO dto, String tableAlias, boolean isOrderBy) {
        final QueryWrapper<UserWalletRechargeLog> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getUserId())) {
                queryWrapper.eq(tableAlias + "user_id", dto.getUserId());
            }
            if (StringUtils.hasLength(dto.getOrderId())) {
                queryWrapper.eq(tableAlias + "order_id", dto.getOrderId());
            }
            if (StringUtils.hasLength(dto.getPlanCode())) {
                queryWrapper.eq(tableAlias + "plan_code", dto.getPlanCode());
            }
            if (StringUtils.hasLength(dto.getOperator())) {
                queryWrapper.eq(tableAlias + "operator", dto.getOperator());
            }
            if (StringUtils.hasLength(dto.getOperateOrgId())) {
                queryWrapper.eq(tableAlias + "operate_org_id", dto.getOperateOrgId());
            }
            if (StringUtils.hasLength(dto.getPublishId())) {
                queryWrapper.eq(tableAlias + "publish_id", dto.getPublishId());
            }
            if(null !=dto.getRechargeType()){
                queryWrapper.eq(tableAlias + "recharge_type", dto.getRechargeType());
            }
            if (null != dto.getPayStatus()) {
                queryWrapper.eq(tableAlias + "pay_status", dto.getPayStatus());
            }
            if (null != dto.getPayStatusArray()) {
                queryWrapper.in(tableAlias + "pay_status", dto.getPayStatusArray());
            }
            if (StringUtils.hasLength(dto.getBeginTime()) && !StringUtils.hasLength(dto.getEndTime())) {
                queryWrapper.between(tableAlias + "recharge_time", dto.getBeginTime() + " 00:00:00", dto.getBeginTime() + " 23:59:59");
            }
            if (!StringUtils.hasLength(dto.getBeginTime()) && StringUtils.hasLength(dto.getEndTime())) {
                queryWrapper.between(tableAlias + "recharge_time", dto.getEndTime() + " 00:00:00", dto.getEndTime() + " 23:59:59");
            }
            if (StringUtils.hasLength(dto.getBeginTime()) && StringUtils.hasLength(dto.getEndTime())) {
                queryWrapper.between(tableAlias + "recharge_time", dto.getBeginTime() + " 00:00:00", dto.getEndTime() + " 23:59:59");
            }
        }
        if (isOrderBy) {
            queryWrapper.orderByDesc(tableAlias + "recharge_time");
            queryWrapper.orderByDesc(tableAlias + "user_id");
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<UserWalletRechargeLog> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<UserWalletRechargeLog> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(UserWalletRechargeLog::getOrderId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(readOnly = true)
    public UserWalletRechargeLog sumRechargeLogByUserId(String userId) {
        QueryWrapper<UserWalletRechargeLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("pay_status", DisplayUtil.PAY_STATUS_1);
        queryWrapper.select("user_id,IFNULL(sum(all_amount),0) AS all_amount," +
                "IFNULL(sum(give_amount),0) AS give_amount,IFNULL(sum(pay_amount),0) AS pay_amount");
        UserWalletRechargeLog userWalletRechargeLog = baseMapper.selectOne(queryWrapper, false);
        queryWrapper.clear();
        if (null == userWalletRechargeLog) {
            userWalletRechargeLog = new UserWalletRechargeLog();
            userWalletRechargeLog.setAllAmount(new BigDecimal("0"));
            userWalletRechargeLog.setGiveAmount(userWalletRechargeLog.getAllAmount());
            userWalletRechargeLog.setPayAmount(userWalletRechargeLog.getPayAmount());
        }
        return userWalletRechargeLog;
    }

    @Transactional(readOnly = true)
    public boolean existsByPlanCode(String planCode) {
        final QueryWrapper<UserWalletRechargeLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plan_code", planCode);
        boolean exists = getBaseMapper().exists(queryWrapper);
        queryWrapper.clear();
        return exists;
    }

    @Transactional(readOnly = true)
    public UserWalletRechargeLogStatisticsDTO sumAmount(UserWalletRechargeLogDTO dto) {
        QueryWrapper<UserWalletRechargeLog> queryWrapper = createQueryWrapper(dto, "t1.", false);
        if(StringUtils.hasLength(dto.getMobile())){
            queryWrapper.eq("t2.mobile", dto.getMobile());
        }
        UserWalletRechargeLogStatisticsDTO userWalletRechargeLogStatisticsDTO = getBaseMapper().sumAmount(queryWrapper);
        if (null == userWalletRechargeLogStatisticsDTO) {
            userWalletRechargeLogStatisticsDTO = new UserWalletRechargeLogStatisticsDTO();
            userWalletRechargeLogStatisticsDTO.setAllAmount(new BigDecimal("0.00"));
            userWalletRechargeLogStatisticsDTO.setGiveAmount(userWalletRechargeLogStatisticsDTO.getAllAmount());
            userWalletRechargeLogStatisticsDTO.setPayAmount(userWalletRechargeLogStatisticsDTO.getAllAmount());
            userWalletRechargeLogStatisticsDTO.setQuantity(0L);
        }
        return userWalletRechargeLogStatisticsDTO;
    }
}